<template>
  <div>
    <div class="top-panel__box">
      <el-form
        :model="dataForm"
        ref="dataForm"
        inline
        size="small"
        onsubmit="return false"
        :rules="rules"
      >
        <el-row>
          <el-form-item label="产品类型" label-width="80px">
            <el-select
              placeholder="产品类型"
              v-model="dataForm.productTypeList"
            >
              <el-option
                v-for="(value, key) of dicts['product_type'].childMap"
                :key="key"
                :label="value"
                :value="key"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="当前状态"
            label-width="80px"
            v-if="
              (flag === 'M' || flag === 'Q') && dataForm.productTypeList != ''
            "
          >
            <el-select
              placeholder="当前状态"
              v-model="dataForm.caseStatusList"
              multiple
              clearable
              collapse-tags
            >
              <el-option
                v-for="(item, key) in nowStatus"
                :key="key"
                :label="item"
                :value="key"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row style="margin:10px 0 0 80px;">
          <el-form-item>
            <el-input
              placeholder="输入进件编号"
              v-model="dataForm.applyNo"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-input
              placeholder="输入申请人姓名/身份证号/手机号"
              style="width:250px"
              v-model="dataForm.freeCondition"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-input
              placeholder="受理人"
              v-model="dataForm.acceptorName"
              maxlength="30"
              clearable
              v-show="flag != 'AS'"
            />
          </el-form-item>
          <el-form-item prop="acceptorOrgNo" v-show="flag != 'AS'">
            <organization-cascader
              v-model="dataForm.acceptorOrgNo"
              :placeholder="'请选择受理人机构'"
            ></organization-cascader>
          </el-form-item>
          <el-form-item prop="enterStartTime">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd"
              v-model="dataForm.beginTime"
              style="width:220px"
              placeholder="申请时间起"
            />
            <span>-</span>
            <el-date-picker
              type="date"
              @change="endChange"
              v-model="dataForm.endTime"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width:220px"
              placeholder="申请时间止"
            />
          </el-form-item>
        </el-row>
        <el-row style="margin:10px 0 0 80px;">
          <el-form-item>
            <el-button type="primary" @click="getList(1)">
              <fa-icon class="fa-search" />查询</el-button
            >
            <el-button
              type="primary"
              v-show="flag === 'M'"
              @click="batchCancel"
              v-permission="'ASSIGN_ACCEPTOR'"
            >
              批量撤回</el-button
            >
            <el-button
              type="primary"
              v-show="flag === 'M'"
              @click="batchAssign"
              v-permission="'ASSIGN_ACCEPTOR'"
            >
              批量分派</el-button
            >
            <el-button plain type="info" @click="reset">
              <fa-icon class="fa-refresh" />重置</el-button
            >
          </el-form-item>
        </el-row>
      </el-form>
      <el-row class="table-top">
        <el-table
          ref="tableRef"
          :row-key="getRowKey"
          @select-all="selectAllEvent"
          :data="dataList"
          v-loading="tableLoading"
          tooltip-effect="light"
          @selection-change="handleSelectionChange"
          :cell-style="addCellStyle"
          class="tc-table-box"
          size="small"
        >
          <el-table-column
            v-if="flag === 'M'"
            type="selection"
            width="55"
            fixed="left"
            :reserve-selection="true"
          ></el-table-column>
          <el-table-column
            type="index"
            width="55"
            fixed="left"
            label="序号"
          ></el-table-column>
          <template v-for="(column, index) in HEAD_LIST[flag]">
            <el-table-column
              :prop="column.prop"
              :label="column.label"
              :key="index"
              :width="column.width"
              :show-overflow-tooltip="true"
            />
          </template>
          <el-table-column
            prop="operation"
            class-name="oper-col"
            label="操作"
            :width="200"
            v-if="flag === 'M'"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="assignRow([scope.row.caseId])"
                v-permission="'ASSIGN_ACCEPTOR'"
                v-if="
                  !scope.row.acceptorName &&
                    scope.row.caseStatus !== 'QUOTA_COMPLETE' &&
                    scope.row.caseStatus !== 'AUDIT_REJECT'
                "
                >分派</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="withdrawRow([scope.row.caseId])"
                v-permission="'ASSIGN_ACCEPTOR'"
                v-if="
                  scope.row.acceptorName &&
                    scope.row.caseStatus !== 'QUOTA_COMPLETE' &&
                    scope.row.caseStatus !== 'AUDIT_REJECT' &&
                    scope.row.caseStatus !== 'FIRST_AUDIT' &&
                    scope.row.caseStatus !== 'RESEARCH'
                "
                >撤回</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="cancelRow([scope.row.caseId])"
                v-if="
                  scope.row.caseStatus !== 'QUOTA_AUDIT' &&
                    scope.row.caseStatus !== 'QUOTA_COMPLETE' &&
                    scope.row.caseStatus !== 'AUDIT_REJECT'
                "
                v-permission="'CANCEL_CONTROL'"
                >取消</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="launchReview(scope.row)"
                v-if="
                  scope.row.caseStatus == 'QUOTA_COMPLETE' ||
                    scope.row.caseStatus == 'AUDIT_REJECT'
                "
                v-permission="'UBUTUATE_RETRUAI'"
                >发起重审</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            v-else
            prop="operation"
            class-name="oper-col"
            label="操作"
            :width="100"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                v-if="flag === 'A'"
                plain
                @click="approvalRow(scope.row)"
                >审核</el-button
              >
              <el-button
                size="mini"
                type="primary"
                v-if="flag === 'AS'"
                plain
                @click="assignRow([scope.row.caseId])"
                >分派</el-button
              >
              <el-button
                size="mini"
                type="primary"
                v-if="flag === 'Q'"
                plain
                @click="approvalRow(scope.row)"
                >详情</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row class="pagination-top">
          <pagination
            :pageNum.sync="dataForm.pageNum"
            :curSizes.sync="dataForm.pageSize"
            :total="total"
            @getList="getList"
          />
        </el-row>
      </el-row>
    </div>
    <!--分派-->
    <el-dialog
      title="分派"
      :visible.sync="assignDialog"
      width="40%"
      :close-on-click-modal="false"
    >
      <assign-acceptor v-if="assignDialog" @uppdataSuccess="uppdataSuccess" />
    </el-dialog>
    <el-dialog
      title="发起重审"
      :visible.sync="showReview"
      width="40%"
      :close-on-click-modal="false"
    >
      <launch-review-com
        v-if="showReview"
        @updataSuccess="updataSuccess"
        @updataClose="updataClose"
      ></launch-review-com>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { HEAD_LIST, CUR_SATUS } from "../js/contant.js";
import api from "../api";
import { CONSTANT_OBJ } from "@/utils/constant";
import LaunchReviewCom from "@/components/launchReviewCom/LaunchReviewCom";
import AssignAcceptor from "@/components/assignAcceptor/AssignAcceptor";
import OrganizationCascader from "@/components/organizationCascader";
import * as tabsRouterName from "@/router/tabComponents";
import { common } from "@/utils/common";
import { disposePhone, encryptIdNo, encryptName } from "@/utils/util";
export default {
  components: { AssignAcceptor, OrganizationCascader, LaunchReviewCom },
  props: { flag: String, status: String },
  data() {
    return {
      tableLoading: false,
      assignDialog: false,
      HEAD_LIST,
      CUR_SATUS,
      editData: {},
      dataForm: {
        productTypeList: "JXD",
        caseStatusList: [],
        caseStatus: this.status || "",
        applyNo: "",
        freeCondition: "",
        acceptorName: "",
        acceptorOrgNo: "",
        menuFlag: "1",
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      slectedList: [],
      selectedIds: [],
      dataList: [],
      showReview: false,
      nowCaseId: "",
      nowStatus: {},
      rules: {
        endTime: [
          { required: true, trigger: "change", validator: this.rulesTime }
        ]
      }
    };
  },
  created() {
    this.disposeNowStatus();
  },
  mounted() {
    this.$store.dispatch("common/queryProductData", {
      pageNum: 1,
      pageSize: 99
    });
    console.log("公共下拉字段", this.dicts);
    switch (this.flag) {
      case "A":
        this.dataForm.menuFlag = "1";
        break;
      case "M":
        this.dataForm.menuFlag = "2";
        break;
      case "AS":
        this.dataForm.menuFlag = "3";
        break;
      case "Q":
        this.dataForm.menuFlag = "4";
        break;
    }
    this.getList();
  },
  watch: {
    "dataForm.productTypeList": {
      handler: function(newVal, oldVal) {
        this.disposeNowStatus();
      },
      deep: true
    }
  },
  methods: {
    // 获取当前状态
    disposeNowStatus() {
      // 进件管理
      if (this.flag === "M") {
        if (this.dataForm.productTypeList == "JXD") {
          this.nowStatus = { ...this.dicts["case_manage_status"].childMap };
        } else if (this.dataForm.productTypeList == "JYD") {
          this.nowStatus = { ...this.dicts["jyd_case_manage_status"].childMap };
        } else {
          this.dataForm.caseStatusList = [];
        }
      }
      // 进件查询
      if (this.flag === "Q") {
        if (this.dataForm.productTypeList == "JXD") {
          this.nowStatus = { ...this.dicts["case_search_status"].childMap };
        } else if (this.dataForm.productTypeList == "JYD") {
          this.nowStatus = { ...this.dicts["jyd_case_search_status"].childMap };
        } else {
          this.dataForm.caseStatusList = [];
        }
      }
    },
    // 列表查询
    getList(val) {
      let dateRes = this.rulesTime();
      if (!dateRes) {
        return;
      }
      this.dataForm.pageNum = val || this.dataForm.pageNum;
      this.tableLoading = true;
      const params = {
        ...this.dataForm
      };
      if (params.productTypeList == "") {
        params.productTypeList = [];
      } else {
        params.productTypeList = [params.productTypeList];
      }
      api
        .postQueryLoanData(params)
        .then(res => {
          const { responseCode, data } = res;
          if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
            this.dataList = data.list || [];
            this.dataList.forEach(item => {
              let statusUpdateTime = new Date(item.statusUpdateTime).getTime();
              let newTime = new Date().getTime();
              let statusStopTime = `${parseInt(
                (newTime - statusUpdateTime) / 60000
              )}min`;
              item.statusStopTime = statusStopTime;
              item.newProductType = this.dicts["product_type"].childMap[
                item.productType
              ];
              item.newGender = this.dicts["gender"].childMap[item.gender];
              item.newPhone = disposePhone(item.customerPhone);
              item.newName = encryptName(item.customerName);
              item.newIdNbr = encryptIdNo(item.idNbr);

              const productType = {
                MJXD: "case_manage_status",
                MJYD: "jyd_case_manage_status",
                QJXD: "case_search_status",
                QJYD: "jyd_case_search_status"
              };

              const val = productType[this.flag + item.productType]
              const dict = this.dicts[val] || {};
              item.newStatus = val ? dict.childMap[item.caseStatus] : '';

            });
            this.total = parseInt(data.total) || 0;
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },

    /**
     * @description 当前状态停留时间：若大于60min，则标记为红色
     */
    addCellStyle({ row: { statusStopTime }, column: { property } }) {
      if (parseInt(statusStopTime) > 60 && property === "statusStopTime") {
        return "color: red";
      }
    },
    disoseStatus(list) {
      return list.map(ele => {
        this.dicts.case_manage_status.childList.forEach(v => {
          if (ele.caseStatus === v.dictNo) {
            ele.newStatus = v.dictName;
          }
        });
        this.dicts.product_type.childList.forEach(v => {
          if (ele.productType === v.dictNo) {
            ele.newProductType = v.dictName;
          }
        });
        return ele;
      });
    },
    // 重置
    reset() {
      Object.keys(this.dataForm).forEach(key => {
        if (typeof this.dataForm[key] === "string") {
          if (key !== "menuFlag" && key !== "caseStatus") {
            this.dataForm[key] = "";
          }
        }
      });
      this.dataForm.pageNum = 1;
      this.dataForm.productTypeList = "JXD";
      this.dataForm.caseStatusList = [];
      this.$nextTick(() => {
        this.getList();
      });
    },
    /**
     * @description 审批 || 查看详情
     */
    approvalRow(row) {
      this.$store.commit("SYNC_APPROVAL_CASE_ID", {
        caseId: row.caseId,
        flag: this.flag
      });
      if (this.$keepAliveList.includes("CASE_DETAIL")) {
        this.$tabRemove("CASE_DETAIL");
      }
      let permissionName =
        this.flag === "A"
          ? `审批-${row.customerName}`
          : `审批详情-${row.customerName}`;
      let permissionCode =
        this.flag === "A"
          ? tabsRouterName.ApprovalCase
          : tabsRouterName.QueryCase;
      this.$openTabs({
        permissionName,
        permissionCode,
        params: row
      });
    },
    // 选中
    handleSelectionChange(val) {
      this.slectedList = val;
      this.selectedIds = [];
      this.slectedList.forEach(item => {
        this.selectedIds.push(item.caseId);
      });
    },
    /**
     * @description 批量分派
     */
    batchAssign() {
      // if (!this.checkoutData1()) {
      //   return false
      // }
      let ids = this.filterData(this.slectedList);
      if (ids.successIndex > 0) {
        common
          .confirmFn(
            `当前已选中进件 ${this.slectedList.length} 笔，其中可分派进件 ${ids.successIndex} 笔。`,
            "是否确定批量分派？"
          )
          .then(res => {
            if (res) {
              this.assignRow(ids.successIds);
            }
          });
      } else {
        common
          .confirmFn(`当前选中的进件中无可分派进件。`, "无可分派进件")
          .then(res => {
            if (res) {
            }
          });
      }
    },
    /**
     * @description 批量撤回
     */
    batchCancel() {
      // if (!this.checkoutData()) {
      //   return false
      // }
      let ids = this.filterData(this.slectedList);
      if (ids.failIndex > 0) {
        common
          .confirmFn(
            `当前已选中进件 ${this.slectedList.length} 笔，其中可撤回分派进件 ${ids.failIndex} 笔。`,
            "是否确定批量撤回分派？"
          )
          .then(res => {
            if (res) {
              api.withdrawAssign({ caseId: ids.failIds }).then(res => {
                this.successFn(res);
              });
            }
          });
      } else {
        common
          .confirmFn(`当前选中的进件中无可撤回分派进件。`, "无可撤回进件")
          .then(res => {
            if (res) {
            }
          });
      }
    },
    // 处理数据
    filterData(ids) {
      let checked = ids.filter(
        v =>
          v.caseStatus !== "QUOTA_COMPLETE" &&
          v.caseStatus !== "AUDIT_REJECT" &&
          !v.acceptorName
      );
      let notCheck = ids.filter(
        v =>
          v.caseStatus !== "QUOTA_COMPLETE" &&
          v.caseStatus !== "AUDIT_REJECT" &&
          v.acceptorName
      );
      console.log(checked, "可分派");
      console.log(notCheck, "不可分派");
      let successIndex = checked.length;
      let failIndex = notCheck.length;
      let successIds = checked.map(ele => ele.caseId);
      let failIds = notCheck.map(ele => ele.caseId);
      return {
        successIndex,
        failIndex,
        failIds,
        successIds
      };
    },
    selectAllEvent(selection) {
      this.slectedList = [...selection];
    },
    getRowKey(row) {
      return row.caseId;
    },
    /**
     * @description 分派
     */
    assignRow(row) {
      this.assignDialog = true;
      this.selectedIds = [...row];
    },
    // 取消
    cancelRow(caseId) {
      common
        .confirmFn("取消后此案件即失效，不可撤回！", "是否确定取消此案件？")
        .then(res => {
          if (res) {
            api.postCancelCaseData({ caseId }).then(res => {
              this.successFn(res);
            });
          }
        });
    },
    // 撤回
    withdrawRow(caseId) {
      common
        .confirmFn("撤回后您可重新进行分派", "是否确定撤回此分派？")
        .then(res => {
          if (res) {
            api.withdrawAssign({ caseId }).then(res => {
              this.successFn(res);
            });
          }
        });
    },
    // 发起重审
    async launchReview({ caseId }) {
      this.nowCaseId = caseId;
      let result = await api.getLaunchNum(caseId);
      console.log(result);
      if (result.responseCode !== "000000") return;
      let title = `<p style="font-weight: bold">无法发起重审。</p>`;
      if (result.data.auditNum > 0) {
        common
          .confirmFn(
            `本月您还可发起 ${result.data.auditNum} 次重审。`,
            "是否确定发起进件重审？"
          )
          .then(res => {
            if (res) {
              this.showReview = true;
            }
          });
      } else {
        common
          .confirmFn(title + "本月您的发起重审次数已用尽。", "", {
            dangerouslyUseHTMLString: true,
            confirmButtonText: "确认",
            type: "warning"
          })
          .then(() => {
            console.log(title);
          })
          .catch(() => {
            return false;
          });
      }
    },
    updataSuccess(reviewData) {
      let params = {
        caseId: this.nowCaseId,
        ...reviewData
      };
      api.launchReviewCase(params).then(res => {
        this.successFn(res);
        this.showReview = false;
      });
    },
    updataClose(close) {
      this.showReview = close;
    },
    /**
     * @description 关闭详情弹框
     */
    uppdataSuccess(acceptorId) {
      console.log(this.selectedIds);
      let data = {
        acceptorId,
        caseIds: this.selectedIds
      };
      console.log(data);
      api.postCaseAssignData(data).then(res => {
        this.successFn(res, "assignDialog");
      });
    },
    successFn(res, dialog) {
      const { responseCode, responseMsg: message } = res;
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: "success"
        });
        if (dialog) {
          this[dialog] = false;
        }
        this.selectedIds = [];
        this.slectedList = [];
        this.$refs.tableRef.clearSelection();
        this.getList(1);
      }
    },
    endChange(end) {
      this.dataForm.endTime = end == null ? end : `${end} 23:59:59`;
    },
    rulesTime() {
      let tempStart = this.dataForm.beginTime;
      let tempEnd = this.dataForm.endTime;
      let start = new Date(tempStart).getTime() || "";
      let end = new Date(tempEnd).getTime() || "";
      if (start && end) {
        if (start > end) {
          this.$message.error("结束时间不能小于开始时间");
          return false;
        } else {
          return true;
        }
      }
      return true;
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
};
</script>

<style lang="less" scoped>
@import "../../../assets/css/common.less";
.table-top {
  margin-top: 20px;
}
// 表格外边框
.tc-table-box {
  border: 1px solid @main-border-color;
  border-bottom: none;
  width: 100%;
}

.el-table thead {
  color: #707277;
}
.tc-table-box th {
  background-color: @panel-color !important;
}
</style>
